package csu.web.credit_bank.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import csu.web.credit_bank.pojo.Resource;
import csu.web.credit_bank.pojo.ResourceRecommendation;
import csu.web.credit_bank.pojo.vo.ResourceVO;
import csu.web.credit_bank.service.ResourceRecommendationsService;
import csu.web.credit_bank.service.ResourceService;
import csu.web.credit_bank.utils.Result;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import java.util.List;
import java.util.Map;
import java.util.NoSuchElementException;

@RestController
@RequestMapping("/resources")
@CrossOrigin
public class ResourceController {

    @Autowired
    private ResourceService resourceService;
    @Autowired
    private ResourceRecommendationsService recommendationsService;

    // --- 学习资源(Resource)本身的CRUD ---
    @PostMapping
    public Result<Resource> createResource(@RequestPart("file") MultipartFile file,
                                           @RequestPart(value = "coverImage", required = false) MultipartFile coverImage,
                                           @RequestPart("resource") Resource resource) {

            System.out.println("---- Backend: createResource API called ----");
            System.out.println("Received file name: " + (file != null ? file.getOriginalFilename() : "NULL"));
            System.out.println("Is file empty? " + (file != null ? file.isEmpty() : "N/A"));
            System.out.println("Received coverImage name: " + (coverImage != null ? coverImage.getOriginalFilename() : "NULL"));
            System.out.println("Is coverImage empty? " + (coverImage != null ? coverImage.isEmpty() : "N/A"));
            System.out.println("Received resource object: " + resource); // 打印整个 resource 对象
            System.out.println("Resource Title: " + resource.getTitle());
            System.out.println("Resource Category: " + resource.getCategory() + ", Type: " + (resource.getCategory() != null ? resource.getCategory().getClass().getSimpleName() : "NULL"));
            System.out.println("Resource PublisherId: " + resource.getPublisherId() + ", Type: " + (resource.getPublisherId() != null ? resource.getPublisherId().getClass().getSimpleName() : "NULL"));
        try {
            // 调用更新后的Service方法，传入两个文件
            Resource createdResource = resourceService.createResourceWithUpload(file, coverImage, resource);
            return Result.success("资源创建成功", createdResource);
        } catch (Exception e) {
            // 统一捕获Service层可能抛出的所有异常
            return Result.failure(e.getMessage());
        }
    }

    // 获取资源列表，支持多条件检索和分页
    @GetMapping
    public Result<IPage<ResourceVO>> searchResources(
            @RequestParam(defaultValue = "1") int page,
            @RequestParam(defaultValue = "10") int size,
            @RequestParam(required = false) String major,
            @RequestParam(required = false) Integer category,
            @RequestParam(required = false) Integer difficulty,
            @RequestParam(required = false) String q,
            @RequestParam(required = false) String sort
    ) {
        Page<Resource> pageInfo = new Page<>(page, size);
        IPage<ResourceVO> results = resourceService.searchResources(pageInfo, major, category, difficulty, q, sort);
        return Result.success(results);
    }

    @GetMapping("/{id}")
    public Result<ResourceVO> getResourceById(@PathVariable String id) {
        ResourceVO resourceVO = resourceService.getResourceVOById(id);
        return resourceVO != null ? Result.success(resourceVO) : Result.failure(404, "资源未找到");
    }

    @PutMapping("/{id}")
    public Result<Resource> updateResourceMetadata(@PathVariable String id, @RequestBody Resource resource) {
        // 这个接口只更新元数据，不更新文件
        resource.setId(id);
        boolean success = resourceService.updateById(resource);
        return success ? Result.success("资源信息更新成功", resource) : Result.failure("资源信息更新失败");
    }

    // 更新指定资源的关联文件
    @PostMapping("/{id}/file")
    public Result<Resource> updateResourceFile(@PathVariable String id, @RequestPart("file") MultipartFile file) {
        try {
            Resource updatedResource = resourceService.updateResourceFile(id, file);
            return Result.success("资源文件更新成功", updatedResource);
        } catch (NoSuchElementException e) {
            return Result.failure(404, e.getMessage());
        } catch (Exception e) {
            return Result.failure(e.getMessage());
        }
    }
    @DeleteMapping("/{id}")
    public Result<Void> deleteResource(@PathVariable String id) {
        boolean success = resourceService.deleteResource(id);
        return success ? Result.success("资源删除成功") : Result.failure("资源删除失败");
    }

    // --- 资源推荐记录(Recommendation)相关操作 ---
    // 当用户浏览某个专业的资源列表时，记录一次浏览行为
    @PostMapping("/recommendations/views")
    public Result<ResourceRecommendation> logResourceView(@RequestBody Map<String, String> payload) {
        String userId = payload.get("userId");
        String major = payload.get("major");
        if (!StringUtils.hasText(userId) || !StringUtils.hasText(major)) {
            return Result.failure("userId 和 major 不能为空");
        }
        try {
            ResourceRecommendation recommendation = recommendationsService.logResourceView(userId, major);
            return Result.success("浏览记录成功", recommendation);
        } catch (Exception e) {
            return Result.failure(e.getMessage());
        }
    }
    // 获取某个用户的所有资源推荐浏览记录
    @GetMapping("/recommendations")
    public Result<List<ResourceRecommendation>> getUserRecommendations(@RequestParam String userId) {
        if (!StringUtils.hasText(userId)) {
            return Result.failure("userId 不能为空");
        }
        List<ResourceRecommendation> recommendations = recommendationsService.getRecommendationsByUserId(userId);
        return Result.success(recommendations);
    }

    // 获取某个用户的个性化资源推荐
    @GetMapping("/users/{userId}/recommendations")
    public Result<IPage<ResourceVO>> getPersonalizedRecommendations(
            @PathVariable String userId,
            @RequestParam(defaultValue = "1") int page,
            @RequestParam(defaultValue = "10") int size
    ) {
        Page<ResourceVO> pageInfo = new Page<>(page, size);
        IPage<ResourceVO> recommendations = resourceService.getPersonalizedRecommendations(userId, pageInfo);
        return Result.success(recommendations);
    }

    @GetMapping("/byPublisher/{publisherId}")
    public Result<List<Resource>> getResourcesByPublisher(
            @PathVariable String publisherId,
            @RequestParam(required = false) String q) {
        if (!StringUtils.hasText(publisherId)) {
            return Result.failure("发布者ID不能为空");
        }

        QueryWrapper<Resource> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("publisher_id", publisherId); // 根据 publisher_id 过滤

        if (StringUtils.hasText(q)) {
            queryWrapper.like("title", q); // 如果有关键词，对 title 进行模糊搜索
        }
        // 调用 ResourceService 获取资源列表
        List<Resource> resources = resourceService.list(queryWrapper);
        return Result.success(resources);
    }

    @GetMapping("/by-publisher/{publisherId}") // 使用新的URL路径以示区分
    public Result<IPage<ResourceVO>> getResourcesByPublisher(
            @PathVariable String publisherId,
            @RequestParam(defaultValue = "1") int page,
            @RequestParam(defaultValue = "12") int size) {
        if (!StringUtils.hasText(publisherId)) {
            return Result.failure("发布者ID不能为空");
        }
        Page<Resource> pageInfo = new Page<>(page, size);

        QueryWrapper<Resource> queryWrapper = new QueryWrapper<>();

        queryWrapper.eq("r.publisher_id", publisherId);
        queryWrapper.orderByDesc("r.id");
        IPage<ResourceVO> results = resourceService.searchResources(pageInfo, queryWrapper);
        return Result.success(results);
    }

}